<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="部门名称:" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门状态:" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="部门状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="small"
          @click="toggleExpandAll"
        >
          展开/折叠
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      ref="deptTree"
      v-if="refreshTable"
      border
      height="730"
      v-loading="loading"
      :data="deptList"
      :row-key="
        (row) => {
          return row.deptId;
        }
      "
      :expand-row-keys="expandsArr"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <!-- @expand-change="handleExpandSelect" -->
      <!-- :default-expand-all="isExpandAll" -->
      <el-table-column
        prop="deptName"
        label="部门名称"
        min-width="260"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column prop="orderNum" label="排序"></el-table-column>
      <el-table-column
        prop="administrativeDivision"
        label="行政区划"
        width="200"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.administrative_division"
            :value="scope.row.administrativeDivision"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="部门类型" width="200">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_dept_type"
            :value="scope.row.type"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="300"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >
            修改
          </el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
          >
            新增
          </el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
            style="color: #f56c6c"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :width="form.type == 4 ? '1400px' : '700px'"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="form.type == 4 ? 12 : 24">
            <!-- 通用字段名称 -->
            <el-row>
              <el-col :span="12" v-if="form.parentId !== 0">
                <el-form-item label="上级部门" prop="parentId">
                  <treeselect
                    v-model="form.parentId"
                    :options="deptOptions"
                    :normalizer="normalizer"
                    placeholder="选择上级部门"
                    class="parent-dept-area"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="显示排序" prop="orderNum">
                  <el-input-number
                    v-model="form.orderNum"
                    controls-position="right"
                    :min="0"
                    size="small"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="行政区划" prop="administrativeDivision">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.administrativeDivision"
                    :modelBinding="'administrativeDivision'"
                    :selectArr="dict.type.administrative_division"
                    :inputWidth="form.type == 4 ? 220 : 210"
                    placeholder="请选择行政区划"
                    size="small"
                    @handleSelect="handleSelect"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门类型" prop="type">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.type"
                    :modelBinding="'type'"
                    :selectArr="dict.type.sys_dept_type"
                    :inputWidth="form.type == 4 ? 220 : 210"
                    placeholder="请选择部门类型"
                    size="small"
                    @handleSelect="handleSelect"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="部门名称" prop="deptName">
                  <el-input
                    v-model.trim="form.deptName"
                    maxlength="30"
                    placeholder="请输入部门名称"
                    size="small"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="form.email"
                    placeholder="请输入邮箱"
                    maxlength="50"
                    size="small"
                  />
                </el-form-item> -->
                <el-form-item
                  label="所属市县"
                  prop="administrativeDivisionName"
                >
                  <el-cascader
                    v-model="form.administrativeDivisionName"
                    :options="DivisionNameoptions"
                    :props="DivisionNameprops"
                    @change="handleDivisionNameChange"
                    @visible-change="handleDivisionNameVisible"
                    size="small"
                  ></el-cascader>
                  <!-- <CascaderSelect
                    :values=""
                    :varient="''"
                    size="small"
                    placeholder=""
                    @input=""
                  ></CascaderSelect> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="部门汇总名称" prop="deptNickname">
                  <el-input
                    v-model.trim="form.deptNickname"
                    maxlength="30"
                    placeholder="请输入部门汇总名称"
                    size="small"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="负责人" prop="leader">
                  <el-input
                    v-model="form.leader"
                    placeholder="请输入负责人"
                    maxlength="20"
                    size="small"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    v-model="form.phone"
                    placeholder="请输入联系电话"
                    maxlength="13"
                    size="small"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="form.email"
                    placeholder="请输入邮箱"
                    maxlength="50"
                    size="small"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="部门状态">
                  <el-radio-group v-model="form.status" size="small">
                    <el-radio
                      v-for="dict in dict.type.sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址" prop="address">
                  <el-input
                    v-model="form.address"
                    placeholder="请输入详细地址"
                    size="small"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24" class="remark-area">
                <span>备注：</span>
                <span>
                  1、部门信息行政区划4级管理，为省级、地市级、区县级、科室级。
                </span>
                <span>
                  2、若部门在能耗组织结构中又多个部门类型，则“用能部门”的部门类型的名称用统一社会信用编码对应的名称，其余部门类型在原部门名称后加后缀。
                </span>
                <span>
                  例如：“舟山市财政局”具有用能部门，能耗预算制定两种部门类型，那么“用能部门”部门类型的名称为“舟山市财政局”，而“能耗预算制定”部门类型的名称为“舟山市财政局能耗预算管理部门”。
                </span>
              </el-col>
            </el-row>
            <el-row v-if="form.type == 4">
              <!-- <el-col :span="12">
                <el-form-item label="分区情况" prop="energySubarea">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.energySubarea"
                    :modelBinding="'energySubarea'"
                    :selectArr="dict.type.energy_subarea_type"
                    @handleSelect="handleSelect"
                    :inputWidth="220"
                    :size="'small'"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="分区子类" prop="energySubareaChild">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.energySubareaChild"
                    :modelBinding="'energySubareaChild'"
                    :selectArr="dict.type.energy_subarea_child_type"
                    @handleSelect="handleSelect"
                    :inputWidth="220"
                    :size="'small'"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col> -->
            </el-row>
          </el-col>
          <el-col :span="form.type == 4 ? 12 : 0" v-if="form.type == 4">
            <!-- 用能部门特殊字段 -->
            <el-row v-if="form.type == 4">
              <el-col :span="12">
                <el-form-item label="分户情况" prop="energyFamilySplitting">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.energyFamilySplitting"
                    :modelBinding="'energyFamilySplitting'"
                    :selectArr="dict.type.energy_family_splitting_type"
                    @handleSelect="handleSelect"
                    :inputWidth="220"
                    :size="'small'"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用能方式" prop="energyWay">
                  <el-radio-group v-model="form.energyWay" size="small">
                    <el-radio
                      v-for="item in energyWayArr"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="form.type == 4">
              <el-col :span="12">
                <el-form-item label="部门经度" prop="latitude">
                  <el-input
                    placeholder="请输入或选择"
                    v-model="form.latitude"
                    maxlength="14"
                    clearable
                    size="small"
                  >
                    <template slot="append">
                      <el-button size="small" @click="openMap">
                        地图
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门纬度" prop="longitude">
                  <el-input
                    placeholder="请输入或选择"
                    v-model="form.longitude"
                    maxlength="14"
                    clearable
                    size="small"
                  >
                    <template slot="append">
                      <el-button size="small" @click="openMap">
                        地图
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="form.type == 4">
              <el-col :span="12">
                <el-form-item label="节能目标" prop="energySavingTarget">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.energySavingTarget"
                    :modelBinding="'energySavingTarget'"
                    :selectArr="dict.type.energy_saving_target"
                    @handleSelect="handleSelect"
                    :inputWidth="220"
                    :size="'small'"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="form.type == 4">
                <el-form-item label="职能分类" prop="functionalClassification">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.functionalClassification"
                    :modelBinding="'functionalClassification'"
                    :selectArr="dict.type.functional_classification_type"
                    @handleSelect="handleSelect"
                    :inputWidth="220"
                    :size="'small'"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="用地面积" prop="landArea">
                  <el-input
                    v-model="form.landArea"
                    size="small"
                    @input="
                      (val) => {
                        replaceDigitDeal(val, 2, 'landArea');
                      }
                    "
                  >
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="办公用能面积" prop="officeEnergyArea">
                  <el-input
                    v-model="form.officeEnergyArea"
                    size="small"
                    @input="
                      (val) => {
                        replaceDigitDeal(val, 2, 'officeEnergyArea');
                      }
                    "
                  >
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row v-if="form.type == 4">
              <el-col :span="12">
                <el-form-item label="省级考核" prop="provincialAssessment">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.provincialAssessment"
                    :modelBinding="'provincialAssessment'"
                    :selectArr="dict.type.provincial_assessment"
                    :inputWidth="220"
                    :size="'small'"
                    @handleSelect="handleSelect"
                  ></DictionariesSelect>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公共机构规模" prop="institutionalSize">
                  <DictionariesSelect
                    :showType="0"
                    :datas="form.institutionalSize"
                    :modelBinding="'institutionalSize'"
                    :selectArr="dict.type.institutional_size"
                    :inputWidth="220"
                    :size="'small'"
                    @handleSelect="handleSelect"
                  ></DictionariesSelect>
                </el-form-item>
                <!-- <div class="extre-span">
                  <span>
                    《行政中心用能预算管理实施方案》舟山市机关事务管理中心（2022.8.31）
                  </span>
                </div> -->
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="公摊用能面积" prop="sharedEnergyArea">
                  <el-input
                    v-model="form.sharedEnergyArea"
                    size="small"
                    @input="
                      (val) => {
                        replaceDigitDeal(val, 2, 'sharedEnergyArea');
                      }
                    "
                  >
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row v-if="form.type == 4">
              <!-- <el-col :span="12">
                <el-form-item label="用能人数" prop="energyUserNumber">
                  <el-input
                    v-model="form.energyUserNumber"
                    size="small"
                    @input="
                      (val) => {
                        replaceIntegerDeal(val, 'energyUserNumber');
                      }
                    "
                  ></el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row v-if="form.type == 4">
              <!-- <el-col :span="12">
                <el-form-item label="编制人数" prop="organizationUserNumber">
                  <el-input
                    v-model="form.organizationUserNumber"
                    size="small"
                    @input="
                      (val) => {
                        replaceIntegerDeal(val, 'organizationUserNumber');
                      }
                    "
                  ></el-input>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="12">
                <el-form-item label="用地面积" prop="landArea">
                  <el-input
                    v-model="form.landArea"
                    size="small"
                    @input="
                      (val) => {
                        replaceDigitDeal(val, 2, 'landArea');
                      }
                    "
                  >
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row v-if="form.type == 4">
              <el-col :span="12">
                <el-form-item label="分户数量" prop="familySplittingVal">
                  <el-input
                    v-model="form.familySplittingVal"
                    size="small"
                    @input="
                      (val) => {
                        replaceIntegerDeal(val, 'familySplittingVal');
                      }
                    "
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- <el-form-item
                  label="所属市县"
                  prop="administrativeDivisionName"
                >
                  <el-cascader
                    v-model="form.administrativeDivisionName"
                    :options="DivisionNameoptions"
                    :props="DivisionNameprops"
                    @change="handleDivisionNameChange"
                    @visible-change="handleDivisionNameVisible"
                    size="small"
                  ></el-cascader>
                </el-form-item> -->
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="分区数量" prop="subareaVal">
                  <el-input
                    v-model="form.subareaVal"
                    size="small"
                    @input="
                      (val) => {
                        replaceIntegerDeal(val, 'subareaVal');
                      }
                    "
                  ></el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row v-if="form.type == 4">
              <!-- <el-col :span="12">
                <el-form-item label="监控设备数量" prop="monitorDeviceVal">
                  <el-input
                    v-model="form.monitorDeviceVal"
                    size="small"
                    @input="
                      (val) => {
                        replaceIntegerDeal(val, 'monitorDeviceVal');
                      }
                    "
                  ></el-input>
                </el-form-item>
              </el-col> -->
            </el-row>
            <!-- <el-row v-if="form.type == 4">
              <el-col :span="24">
                <el-form-item label="详细位置" prop="roomId">
                  <div class="location-area">
                    <div class="location-item">
                      <el-select
                        v-model="form.parkId"
                        placeholder="请选择园区"
                        @visible-change="handleGetParkList"
                        @change="handleSelectlocation(0)"
                        :style="'width:' + locationInputwidth + 'px'"
                        size="small"
                      >
                        <el-option
                          v-for="item in parkArr"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                      <div class="append">园区</div>
                    </div>
                    <div class="location-item">
                      <el-select
                        v-model="form.buildingId"
                        placeholder="请选择楼幢"
                        @visible-change="handleGetBuildingList"
                        @change="handleSelectlocation(1)"
                        :style="'width:' + locationInputwidth + 'px'"
                        size="small"
                      >
                        <el-option
                          v-for="item in buildingArr"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                      <div class="append">楼（幢）</div>
                    </div>
                    <div class="location-item">
                      <el-select
                        v-model="form.facilitiesIds"
                        placeholder="请选择楼层"
                        multiple
                        clearable
                        @clear="handleClearfa"
                        @visible-change="handleGetFacilitiesList"
                        @remove-tag="handleRemovefa"
                        @change="handleSelectlocation(2)"
                        :style="'width:' + locationInputwidth + 'px'"
                        size="small"
                      >
                        <el-option
                          v-for="item in facilitiesArr"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                      <div class="append">楼层（区）</div>
                    </div>
                    <div class="location-item">
                      <el-select
                        v-model="form.roomId"
                        placeholder="请选择房间"
                        multiple
                        clearable
                        @visible-change="handleGetRoomList"
                        @change="handleSelectlocation(3)"
                        :style="'width:' + locationInputwidth + 'px'"
                        size="small"
                      >
                        <el-option
                          v-for="item in roomArr"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        >
                        </el-option>
                      </el-select>
                      <div class="append">房间（区块）</div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row> -->
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitForm">
          确 定
        </el-button>
        <el-button size="small" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <tdMap
      :isShowCreateDialog.sync="mapShow"
      :data="mapData"
      @close="close"
      @result="getLatlng"
    >
    </tdMap>
  </lb-layout>
</template>

<script>
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
  getParkList,
  getBuildingList,
  getFacilitiesList,
  getRoomList,
  patchCascading,
} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import tdMap from "@/components/netWorkmap/map";
import DictionariesSelect from "@/components/DictionariesSelect/index.vue";
import { deepClone, replaceDigit, replaceInteger } from "@/utils/index";
import CascaderSelect from "@/components/Select/CascaderSelect";
// import { set } from "vue/types/umd";

export default {
  name: "Dept",
  dicts: [
    "sys_normal_disable",
    "administrative_division",
    "sys_dept_type",
    "energy_saving_target",
    "provincial_assessment",
    "institutional_size",
    "functional_classification_type",
    "energy_family_splitting_type",
    "energy_subarea_type",
    "energy_subarea_child_type",
  ],
  components: {
    Treeselect,
    tdMap,
    DictionariesSelect,
    CascaderSelect,
  },
  data() {
    return {
      mapShow: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 展开的部门的ID集合
      expandsArr: [],
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined,
      },
      mapData: {
        lat: "",
        lng: "",
      },
      energyWayArr: [
        {
          label: "常规用能",
          value: 0,
        },
        {
          label: "特殊用能",
          value: 1,
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" },
        ],
        administrativeDivision: [
          { required: true, message: "行政区划不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "部门类型不能为空", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        deptNickname: [
          { required: true, message: "部门汇总名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ],
        // email: [
        //   {
        //     type: "email",
        //     message: "请输入正确的邮箱地址",
        //     trigger: ["blur", "change"],
        //   },
        // ],
        phone: [
          {
            // pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        // 用能部门相关
        latitude: [
          {
            required: true,
            message: "请输入或选择能耗部门经度",
            trigger: ["blur", "change"],
          },
        ],
        longitude: [
          {
            required: true,
            message: "请输入或选择能耗部门纬度",
            trigger: ["blur", "change"],
          },
        ],
        functionalClassification: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        energyFamilySplitting: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        // energySubarea: [
        //   { required: true, message: "不能为空", trigger: "blur" },
        // ],
        // energySubareaChild: [
        //   { required: true, message: "不能为空", trigger: "blur" },
        // ],
        energyWay: [{ required: true, message: "不能为空", trigger: "change" }],
        energySavingTarget: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        // officeEnergyArea: [
        //   { required: true, message: "面积不能为空", trigger: "blur" },
        // ],
        // energyUserNumber: [
        //   { required: true, message: "人数不能为空", trigger: "blur" },
        // ],
        // organizationUserNumber: [
        //   { required: true, message: "人数不能为空", trigger: "blur" },
        // ],
        // provincialAssessment: [
        //   { required: false, message: "不能为空", trigger: "blur" },
        // ],
        institutionalSize: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        // sharedEnergyArea: [
        //   { required: true, message: "面积不能为空", trigger: "blur" },
        // ],
        familySplittingVal: [
          { required: true, message: "数量不能为空", trigger: "blur" },
        ],
        administrativeDivisionName: [
          { required: true, message: "市县不能为空", trigger: "blur" },
        ],
        // subareaVal: [
        //   { required: true, message: "数量不能为空", trigger: "blur" },
        // ],
        // monitorDeviceVal: [
        //   { required: true, message: "数量不能为空", trigger: "blur" },
        // ],
        // landArea: [
        //   { required: true, message: "面积不能为空", trigger: "blur" },
        // ],
        // roomId: [
        //   {
        //     required: true,
        //     message: "详细位置必须精确到房间（区块）",
        //     trigger: "blur",
        //   },
        // ],
      },
      parkArr: [],
      buildingArr: [],
      facilitiesArr: [],
      roomArr: [],
      locationInputwidth: 160,
      DivisionNameoptions: [], // 所属区县集合
      DivisionNameprops: {
        // type: Object,
        // default: () => ({
        value: "areaId",
        children: "children",
        label: "name",
        checkStrictly: true,
        expandTrigger: "hover",
        // }),
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {},
  methods: {
    patchCascadingRequest(id) {
      patchCascading(id).then((res) => {
        if (res.code === 700) {
          this.$message.warning(res.msg);
          return false;
        }
        let arr = res ?? [];
        // console.log(arr, "DivisionNameoptions");
        this.DivisionNameoptions = [...arr];
      });
    },
    handleDivisionNameVisible(flag) {
      if (flag) {
        /* 查询舟山市 */
        this.patchCascadingRequest(130);
      }
    },
    handleDivisionNameChange(value) {
      if (value && value.length > 0) {
        this.form.administrativeDivisionName = value[value.length - 1];
      }
    },
    handleSelect(val, flage) {
      this.form[flage] = val;
      // console.log(flage, val);
    },
    getLatlng(e) {
      const { lat, lng } = e;
      console.log(e, "map");
      this.form.latitude = lat.toFixed(7);
      this.form.longitude = lng.toFixed(7);
    },
    // 选择地图
    openMap() {
      this.mapShow = true;
    },
    // 限制输入保留小数位数
    replaceDigitDeal(val, dit, flage) {
      this.form[flage] = replaceDigit(val, dit);
    },
    // 限制输入整数
    replaceIntegerDeal(val, flage) {
      this.form[flage] = replaceInteger(val);
    },
    close(status) {
      this.mapShow = false;
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then((response) => {
        console.log(response, "list");
        this.deptList = this.handleTree(response.data, "deptId");
        console.log(this.deptList, "deptList");
        this.loading = false;
        this.defaultExpandedfirst();
      });
    },
    /** 默认展开表格树结构第一层 */
    defaultExpandedfirst() {
      this.$nextTick(() => {
        this.$refs.deptTree.toggleRowExpansion(this.deptList[0], true);
      });
      this.expandsArr.push(this.deptList[0].deptId);
    },
    //! 对某一行展开或者关闭 --后续研究，暂时未实现
    handleExpandSelect(row, expandedRows) {
      console.log(row, expandedRows);
      this.expandsArr = [this.deptList[0].deptId];
      if (expandedRows) {
        row ? this.expandsArr.push(row.deptId) : "";
        // row ? this.$set(this.expandsArr,[],row.deptId)
      }
      console.log(this.expandsArr);
      // let biggestparentId = this.deptList[0].deptId;
      // let expandsArr = this.expandsArr;
      // if (expandedRows) {
      //   // 第一层一行展开其他行关闭
      //   if (row.parentId == biggestparentId) {
      //     expandsArr = [biggestparentId];
      //     expandsArr.push(row.deptId);
      //   } else {
      //     if (expandsArr.indexOf(row.deptId) < 0) {
      //       expandsArr.push(row.deptId);
      //     }
      //   }
      // } else {
      //   if (expandsArr.indexOf(row.deptId) > 0) {
      //     expandsArr.splice(expandsArr.indexOf(row.deptId), 1);
      //   }
      // }
      // console.log(expandsArr, this.deptList);
      // this.$forceUpdate();
      // this.expandsArr = [];
      // this.$nextTick(() => {
      //   this.expandsArr = expandsArr;
      //   // this.closeExpandRow(this.deptList, false);
      // });
      // this.$refs.deptTree.toggleRowExpansion();
    },
    // 关闭所有展开行
    closeExpandRow(data, isExpansion) {
      data.forEach((item) => {
        this.$refs.deptTree.toggleRowExpansion(item, isExpansion);
        if (item.children.length > 0) {
          this.closeExpandRow(item.children, isExpansion);
        }
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        deptNickname: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        // email: undefined,
        status: "0",
        address: undefined,
        type: undefined,
        administrativeDivision: undefined,
        // 用能部门相关
        latitude: undefined,
        longitude: undefined,
        functionalClassification: undefined, // 职能分类
        energyFamilySplitting: undefined, // 分户情况
        // energySubarea: undefined, // 分区情况
        // energySubareaChild: undefined, // 分区子类
        energyWay: 0,
        energySavingTarget: undefined, // 节能目标
        provincialAssessment: undefined, // 省级考核
        institutionalSize: undefined, // 公共机构规模
        // officeEnergyArea: undefined, // 办公用能面积
        // sharedEnergyArea: undefined, // 公摊用能面积
        // landArea: undefined, // 用地面积
        // energyUserNumber: undefined, // 用能人数
        // organizationUserNumber: undefined, //  编制人数
        // parkId: undefined, // 园区ID
        // buildingId: undefined, // 楼幢ID
        // facilitiesIds: [], // 楼层ID
        // roomId: [], // 房间ID
        familySplittingVal: undefined, // 应设置分户数量
        administrativeDivisionName: undefined, // 所属市县
        // subareaVal: undefined, // 应设置分区数量
        // monitorDeviceVal: undefined, // 应设置计量监控设备数量
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "添加部门";
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 - 查询详情 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then((response) => {
        this.patchCascadingRequest(130);
        setTimeout(() => {
          this.form = this.detailDeal(response?.data ?? {});
          this.open = true;
          this.title = "修改部门";
        }, 300);
      });
      listDeptExcludeChild(row.deptId).then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    // 详情处理
    detailDeal(data) {
      let result = { ...data };
      // 部门类型属于用能部门时
      if (result.type == 4) {
        if (typeof result.functionalClassification == "number") {
          result.functionalClassification =
            result?.functionalClassification.toString() ?? undefined;
        }
        if (typeof result.energyFamilySplitting == "number") {
          result.energyFamilySplitting =
            result?.energyFamilySplitting.toString() ?? undefined;
        }
        // if (typeof result.energySubarea == "number") {
        //   result.energySubarea = result?.energySubarea.toString() ?? undefined;
        // }
        // if (typeof result.energySubareaChild == "number") {
        //   result.energySubareaChild =
        //     result?.energySubareaChild.toString() ?? undefined;landArea
        // }
        if (typeof result.energySavingTarget == "number") {
          result.energySavingTarget =
            result?.energySavingTarget.toString() ?? undefined;
        }
        if (typeof result.provincialAssessment == "number") {
          result.provincialAssessment =
            result?.provincialAssessment.toString() ?? undefined;
        }
        if (typeof result.institutionalSize == "number") {
          result.institutionalSize =
            result?.institutionalSize.toString() ?? undefined;
        }
        if (typeof result.administrativeDivisionName == "string") {
          result.administrativeDivisionName =
            Number(result?.administrativeDivisionName) ?? undefined;
        }
        // result.officeEnergyArea = result?.officeEnergyArea / 100 ?? undefined;
        // result.sharedEnergyArea = result?.sharedEnergyArea / 100 ?? undefined;
        // result.landArea = result?.landArea / 100 ?? undefined;
        // // 详细位置赋值
        // let locationArr = result?.architectureInfoVo ?? [];
        // if (locationArr.length > 0) {
        //   result.parkId = locationArr[0].parkId;
        //   result.buildingId = locationArr[0].buildingId;
        //   result.facilitiesIds = this.removeDuplicate(
        //     locationArr,
        //     "facilitiesId"
        //   );
        //   result.roomId = [];
        //   locationArr.map((item) => {
        //     result.roomId.push(item.roomId);
        //   });
        // }
        // 经纬度赋予
        this.mapData.lat = result?.latitude ?? null;
        this.mapData.lng = result?.longitude ?? null;
        // 详细位置反显
        // setTimeout(() => {
        //   this.locationTeam();
        // }, 100);
      }
      // console.log(result, "详情");
      return result;
    },
    // removeDuplicate(arr, flag) {
    //   let result = [];
    //   arr.map((item, index) => {
    //     if (result.length == 0) {
    //       result.push(item[flag]);
    //     } else {
    //       if (result.indexOf(item[flag]) == -1) {
    //         result.push(item[flag]);
    //       }
    //     }
    //   });
    //   return result;
    // },
    // 详细位置反显
    // locationTeam() {
    //   this.handleGetParkList(true);
    //   this.handleGetBuildingList(true);
    //   this.handleGetFacilitiesList(true);
    //   this.handleGetRoomList(true);
    // },
    // 请求参数处理
    paramsDeal(form) {
      let params = { ...form };
      // 用能部门
      if (params.type == 4) {
        // params.architectureRoomIds = "";
        // params.roomId.map((item, index) => {
        //   if (index + 1 == params.roomId.length) {
        //     params.architectureRoomIds += item;
        //   } else {
        //     params.architectureRoomIds += item + ",";
        //   }
        // });
        // params.officeEnergyArea = params.officeEnergyArea * 100;
        // params.sharedEnergyArea = params.sharedEnergyArea * 100;
        // params.landArea = params.landArea * 100;
        if (typeof params.functionalClassification == "string") {
          params.functionalClassification = Number(
            params.functionalClassification
          );
        }
        if (typeof params.energyFamilySplitting == "string") {
          params.energyFamilySplitting = Number(params.energyFamilySplitting);
        }
        // if (typeof params.energySubarea == "string") {
        //   params.energySubarea = Number(params.energyFamilySplitting);
        // }
        // if (typeof params.energySubareaChild == "string") {
        //   params.energySubareaChild = Number(params.energySubareaChild);
        // }
        if (typeof params.energySavingTarget == "string") {
          params.energySavingTarget = Number(params.energySavingTarget);
        }
        if (typeof params.provincialAssessment == "string") {
          params.provincialAssessment = Number(params.provincialAssessment);
        }
        if (typeof params.institutionalSize == "string") {
          params.institutionalSize = Number(params.institutionalSize);
        }
      } else {
        // params.architectureRoomIds = null;
      }
      // params.roomId = null;
      console.log(params, "qqcs");
      return params;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = this.paramsDeal(this.form);
          // debugger;
          if (this.form.deptId != undefined) {
            updateDept(params).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept(params).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.deptName + '"的数据项？')
        .then(function () {
          return delDept(row.deptId);
        })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 详细地址操作
    // handleSelectlocation(flag) {
    //   console.log(flag);
    //   switch (flag) {
    //     case 0:
    //       this.form.buildingId = undefined;
    //       this.form.facilitiesIds = [];
    //       this.form.roomId = [];
    //       break;
    //     case 1:
    //       this.form.facilitiesIds = [];
    //       this.form.roomId = [];
    //       break;
    //     case 2:
    //       this.form.roomId = [];
    //       break;
    //   }
    // },
    // 获取园区集合
    // handleGetParkList(flag) {
    //   if (flag) {
    //     this.parkArr = [];
    //     getParkList()
    //       .then((res) => {
    //         if (res.code === 700) {
    //           this.$message.warning(res.msg);
    //           return false;
    //         }
    //         // console.log(res, "园区");
    //         let arr = res?.data ?? [];
    //         if (arr.length > 0) {
    //           arr.map((item) => {
    //             let obj = {
    //               id: item.id,
    //               name: item.name,
    //             };
    //             this.parkArr.push(obj);
    //           });
    //         }
    //       })
    //       .catch(() => {});
    //   }
    // },
    // 获取楼幢集合
    // handleGetBuildingList(flag) {
    //   let params = this.form.parkId;
    //   if (flag) {
    //     if (params == "" || params == undefined || params == null) {
    //       this.$message.warning("请先选择园区");
    //       return false;
    //     }
    //     this.buildingArr = [];
    //     this.facilitiesArr = [];
    //     this.roomArr = [];
    //     getBuildingList(params)
    //       .then((res) => {
    //         if (res.code === 700) {
    //           this.$message.warning(res.msg);
    //           return false;
    //         }
    //         // console.log(res, "楼幢");
    //         let arr = res?.data ?? [];
    //         if (arr.length > 0) {
    //           arr.map((item) => {
    //             let obj = {
    //               id: item.id,
    //               name: item.name,
    //             };
    //             this.buildingArr.push(obj);
    //           });
    //         } else {
    //           this.$message.warning("请该园区下楼幢不存在");
    //         }
    //       })
    //       .catch(() => {});
    //   }
    // },
    // 多选模式下移除楼层时触发
    // handleRemovefa(val) {
    //   // console.log(val, 77);
    //   this.form.roomId = [];
    // },
    // 清空楼层
    // handleClearfa() {
    //   this.form.roomId = [];
    // },
    // 获取楼层集合
    // handleGetFacilitiesList(flag) {
    //   let params = this.form.buildingId;
    //   if (flag) {
    //     if (params == "" || params == undefined || params == null) {
    //       this.$message.warning("请先选择楼幢");
    //       return false;
    //     }
    //     this.facilitiesArr = [];
    //     this.roomArr = [];
    //     getFacilitiesList(params)
    //       .then((res) => {
    //         if (res.code === 700) {
    //           this.$message.warning(res.msg);
    //           return false;
    //         }
    //         // console.log(res, "楼层");
    //         let arr = res?.rows ?? [];
    //         if (arr.length > 0) {
    //           arr.map((item) => {
    //             let obj = {
    //               id: item.id,
    //               name: item.name,
    //               // name: item.name + "_" + item.floor.toString() + "层",
    //             };
    //             this.facilitiesArr.push(obj);
    //           });
    //         } else {
    //           this.$message.warning("该楼幢下楼层不存在");
    //         }
    //       })
    //       .catch(() => {});
    //   }
    // },
    // 获取房间集合
    // handleGetRoomList(flag) {
    //   let params = this.form.facilitiesIds;
    //   if (flag) {
    //     if (params == "" || params == undefined || params == null) {
    //       this.$message.warning("请先选择楼层");
    //       return false;
    //     }
    //     this.roomArr = [];
    //     getRoomList(params)
    //       .then((res) => {
    //         if (res.code === 700) {
    //           this.$message.warning(res.msg);
    //           return false;
    //         }
    //         // console.log(res, "房间");
    //         let arr = res?.data ?? [];
    //         if (arr.length > 0) {
    //           arr.map((item) => {
    //             let obj = {
    //               id: item.id,
    //               name:
    //                 item.remarks + item.roomStartNum + "——" + item.roomEndNum,
    //             };
    //             this.roomArr.push(obj);
    //           });
    //         } else {
    //           this.$message.warning("该楼层下房间不存在");
    //         }
    //       })
    //       .catch(() => {});
    //   }
    // },
  },
};
</script>

<style lang="scss" scpoed>
.extre-span {
  width: 330px;
  span {
    width: 310px;
    float: right;
  }
}
.location-area {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  .location-item {
    display: flex;
    margin-bottom: 22px;
    // height: 58px;
    .append {
      width: 84px;
      margin-left: 6px;
    }
  }
}
.remark-area {
  display: flex;
  flex-wrap: wrap;
  width: 95%;
  margin-left: 5%;
  span {
    width: 100%;
    color: #888888;
    font-size: 13px;
  }
}
.parent-dept-area {
  height: 24px !important;
  ::v-deep .vue-treeselect__control {
    height: 22px !important;
  }
}
</style>
